import React, { useState } from 'react'
import { postChatGLMMessageXhr } from '~/api/index'

interface Message {
  content: string
  isUser: boolean
  timestamp: number
}
interface AIProps {
  isOpen: boolean
  onClose: () => void
}

const AIChat = (props: AIProps) => {
  const { isOpen, onClose } = props
  const [messages, setMessages] = useState<Message[]>([])
  const [inputMessage, setInputMessage] = useState('')
  const [loading, setLoading] = useState(false)

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || loading) return

    const userMessage: Message = {
      content: inputMessage,
      isUser: true,
      timestamp: Date.now(),
    }

    setMessages((prev) => [...prev, userMessage])
    setInputMessage('')
    setLoading(true)

    try {
      const response = await postChatGLMMessageXhr({
        message: userMessage?.content,
      })

      if (response?.code === 200) {
        const aiMessage: Message = {
          content: response.data?.choices?.[0]?.message?.content || '',
          isUser: false,
          timestamp: Date.now(),
        }
        setMessages((prev) => [...prev, aiMessage])
      } else {
        throw new Error(response?.message || '请求失败')
      }
    } catch (error) {
      console.error('Chat error:', error)
      const errorMessage: Message = {
        content: '抱歉,我遇到了一些问题,请稍后再试',
        isUser: false,
        timestamp: Date.now(),
      }
      setMessages((prev) => [...prev, errorMessage])
    } finally {
      setLoading(false)
    }
  }
  const handleClose = () => {
    onClose?.()
  }
  return (
    <>
      {/* 对话窗口 */}
      {isOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg w-full max-w-2xl m-4 shadow-xl">
            <div className="flex justify-between items-center p-4 border-b dark:border-gray-700">
              <h3 className="text-xl font-bold">AI助手</h3>
              <button
                onClick={handleClose}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
              >
                <i className="ri-close-line text-2xl"></i>
              </button>
            </div>

            {/* 聊天消息列表 */}
            <div className="h-[400px] overflow-y-auto p-4 space-y-4">
              {messages.map((message, index) => (
                <div
                  key={index}
                  className={`flex ${
                    message.isUser ? 'justify-end' : 'justify-start'
                  }`}
                >
                  <div
                    className={`max-w-[70%] p-3 rounded-lg ${
                      message.isUser
                        ? 'bg-blue-500 text-white'
                        : 'bg-gray-100 dark:bg-gray-700'
                    }`}
                  >
                    {message.content}
                  </div>
                </div>
              ))}
            </div>

            {/* 输入区域 */}
            <div className="p-4 border-t dark:border-gray-700">
              <div className="flex gap-2">
                <input
                  type="text"
                  value={inputMessage}
                  onChange={(e) => setInputMessage(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                  placeholder="输入消息..."
                  className="flex-1 p-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800"
                />
                <button
                  onClick={handleSendMessage}
                  className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  )
}

export default AIChat
